<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>心血管患者个性化生活方式建议系统</title>
    <link rel="icon" href="data:,">
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background-color: #f5f5f5;
            color: #333;
        }
        .container {
            max-width: 900px;
            margin: 20px auto;
            padding: 20px;
            background-color: #fff;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            border-radius: 8px;
        }
        .section {
            margin-bottom: 25px;
            padding: 20px;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            background-color: #fff;
        }
        .section h2 {
            color: #2c3e50;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid #3498db;
        }
        .form-group {
            margin-bottom: 15px;
            display: flex;
            align-items: center;
        }
        label {
            display: inline-block;
            width: 220px;
            color: #2c3e50;
        }
        input[type="number"], input[type="text"], select {
            width: 200px;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        input:focus, select:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 5px rgba(52,152,219,0.3);
        }
        .error-message {
            color: #e74c3c;
            font-size: 12px;
            margin-left: 220px;
            display: none;
        }
        #bmi {
            background-color: #f8f9fa;
            padding: 8px;
            border-radius: 4px;
            font-weight: bold;
            color: #2c3e50;
        }
        button[type="submit"] {
            background-color: #3498db;
            color: white;
            padding: 12px 25px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 20px;
            transition: background-color 0.3s;
        }
        button[type="submit"]:hover {
            background-color: #2980b9;
        }
        .loading {
            display: none;
            text-align: center;
            margin: 20px 0;
        }
        .loading::after {
            content: "处理中...";
            animation: dots 1.5s infinite;
        }
        @keyframes dots {
            0%, 20% { content: "处理中."; }
            40% { content: "处理中.."; }
            60%, 100% { content: "处理中..."; }
        }
        #result {
            margin-top: 30px;
            padding: 20px;
            background-color: #f8f9fa;
            border-radius: 8px;
        }
        #recommendation {
            line-height: 1.6;
            white-space: pre-line;
        }
        .recommendation-section {
            margin-bottom: 20px;
            padding: 15px;
            background-color: #f8f9fa;
            border-radius: 6px;
        }
        .recommendation-title {
            font-size: 1.2em;
            color: #2c3e50;
            margin-bottom: 10px;
            font-weight: bold;
        }
        .recommendation-content {
            margin-left: 20px;
        }
        .recommendation-item {
            margin: 8px 0;
            position: relative;
            padding-left: 20px;
        }
        .recommendation-item:before {
            content: "•";
            position: absolute;
            left: 0;
            color: #3498db;
        }
        .checkbox-group {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
        }
        .checkbox-label {
            display: flex;
            align-items: center;
            gap: 5px;
            cursor: pointer;
        }
        .checkbox-label input[type="checkbox"] {
            width: auto;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>心血管患者个性化生活方式建议系统</h1>
        <form id="patientForm" onsubmit="submitForm(event)">
            <!-- 基本信息 -->
            <div class="section">
                <h2>基本信息</h2>
                <div class="form-group">
                    <label>患者编号：</label>
                    <input type="number" name="patientId" required>
                </div>
                <div class="form-group">
                    <label>身高 (cm)：</label>
                    <input type="number" name="height" id="height" onchange="calculateBMI()" required>
                </div>
                <div class="form-group">
                    <label>体重 (kg)：</label>
                    <input type="number" name="weight" id="weight" onchange="calculateBMI()" required>
                </div>
                <div class="form-group">
                    <label>BMI：</label>
                    <span id="bmi">-</span>
                </div>
                <div class="form-group">
                    <label>体脂率 (%)：</label>
                    <input type="number" name="bodyFat" required>
                </div>
                <div class="form-group">
                    <label>血压 (mmHg)：</label>
                    <input type="number" name="systolic" id="systolic" placeholder="收缩压" required>
                    /
                    <input type="number" name="diastolic" id="diastolic" placeholder="舒张压" required>
                </div>
                <div class="form-group">
                    <label>心率 (次/分)：</label>
                    <input type="number" name="heartRate" required>
                </div>
                <div class="form-group">
                    <label>年龄：</label>
                    <input type="number" name="age" required>
                </div>
            </div>

            <!-- 活动能力 -->
            <div class="section">
                <h2>活动能力</h2>
                <div class="form-group">
                    <label>基本日常生活活动能力：</label>
                    <select name="basicActivity" required>
                        <option value="无">无基本日常获得能力</option>
                        <option value="吃力">基本日常活动吃力</option>
                        <option value="能完成">能完成基本日常活动</option>
                        <option value="轻松">轻松完成基本日常活动</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>工具性日常生活活动能力：</label>
                    <select name="instrumentalActivity" required>
                        <option value="无">无工具性日常活动能力</option>
                        <option value="吃力">工具性日常活动吃力</option>
                        <option value="能完成">能完成工具性日常活动</option>
                        <option value="轻松">轻松完成工具性日常活动能力</option>
                    </select>
                </div>
            </div>

            <!-- 添加既往史部分 -->
            <div class="section">
                <h2>既往史</h2>
                <div class="form-group">
                    <label>是否患有高血压：</label>
                    <select name="hypertension" required>
                        <option value="否">否</option>
                        <option value="是">是</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>是否患有冠心病：</label>
                    <select name="coronaryDisease" required>
                        <option value="否">否</option>
                        <option value="是">是</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>是否患有心力衰竭：</label>
                    <select name="heartFailure" required>
                        <option value="否">否</option>
                        <option value="是">是</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>是否患有糖尿病：</label>
                    <select name="diabetes" required>
                        <option value="否">否</option>
                        <option value="是">是</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>是否患有高血脂：</label>
                    <select name="hyperlipidemia" required>
                        <option value="否">否</option>
                        <option value="是">是</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>当前用药：</label>
                    <input type="text" name="currentMedication" placeholder="请输入药物名称">
                </div>
            </div>

            <!-- 添加饮食习惯部分 -->
            <div class="section">
                <h2>饮食习惯</h2>
                <div class="form-group">
                    <label>饮食偏好（可多选）：</label>
                    <div class="checkbox-group">
                        <label class="checkbox-label">
                            <input type="checkbox" name="dietPreference" value="喜咸"> 喜咸
                        </label>
                        <label class="checkbox-label">
                            <input type="checkbox" name="dietPreference" value="喜甜"> 喜甜
                        </label>
                        <label class="checkbox-label">
                            <input type="checkbox" name="dietPreference" value="素食"> 素食
                        </label>
                        <label class="checkbox-label">
                            <input type="checkbox" name="dietPreference" value="荤食"> 荤食
                        </label>
                    </div>
                </div>
                <div class="form-group">
                    <label>饮食禁忌：</label>
                    <input type="text" name="dietaryRestrictions" placeholder="如：乳糖不耐受">
                </div>
            </div>

            <!-- 在饮食习惯section后添加 -->
            <div class="section">
                <h2>心理状态</h2>
                <div class="form-group">
                    <label>是否存在焦虑：</label>
                    <select name="anxiety" required>
                        <option value="否">否</option>
                        <option value="是">是</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>是否存在抑郁情绪：</label>
                    <select name="depression" required>
                        <option value="否">否</option>
                        <option value="是">是</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>对生活方式改变的信心与动机：</label>
                    <select name="motivation" required>
                        <option value="无">无</option>
                        <option value="有">有</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>睡眠质量：</label>
                    <select name="sleepQuality" required>
                        <option value="不足6小时">不足6小时</option>
                        <option value="6至8小时">6至8小时</option>
                        <option value="8小时以上">8小时以上</option>
                    </select>
                </div>
            </div>

            <!-- 在心理状态section后添加 -->
            <div class="section">
                <h2>生活习惯与环境</h2>
                <div class="form-group">
                    <label>是否吸烟：</label>
                    <select name="smoking" required>
                        <option value="否">否</option>
                        <option value="是">是</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>是否饮酒：</label>
                    <select name="drinking" required>
                        <option value="否">否</option>
                        <option value="是">是</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>工作性质：</label>
                    <select name="workType" required>
                        <option value="久坐">久坐</option>
                        <option value="体力劳动">体力劳动</option>
                    </select>
                </div>
            </div>

            <!-- 在生活习惯与环境section后添加 -->
            <div class="section">
                <h2>遗传与家族史</h2>
                <div class="form-group">
                    <label>心血管疾病家族史：</label>
                    <select name="familyHistory" required>
                        <option value="否">否</option>
                        <option value="是">是</option>
                    </select>
                </div>
            </div>

            <button type="submit">生成个性化建议</button>
        </form>
        
        <div class="loading" id="loading"></div>
        
        <div id="result" class="section" style="display: none;">
            <h2>个性化建议</h2>
            <div id="recommendation"></div>
        </div>
    </div>

    <script>
        // 修改表单验证函数
        function validateForm() {
            console.log('Starting form validation...'); // 调试日志
            
            const height = document.getElementById('height')?.value;
            const weight = document.getElementById('weight')?.value;
            const age = document.getElementById('age')?.value;
            const systolic = document.getElementById('systolic')?.value;
            const diastolic = document.getElementById('diastolic')?.value;
            const dietPreferences = document.querySelectorAll('input[name="dietPreference"]:checked');
            
            console.log('Validation values:', { height, weight, age, systolic, diastolic }); // 调试日志
            
            let isValid = true;
            
            // 验证饮食偏好是否至少选择一项
            if (dietPreferences.length === 0) {
                alert('请至少选择一个饮食偏好');
                isValid = false;
            }
            
            // 身高验证 (放宽范围)
            if (height) {
                if (height < 50 || height > 250) {
                    showError('height', '身高必须在50-250cm之间');
                    console.log('Height validation failed:', height);
                    isValid = false;
                }
            }
            
            // 体重验证 (放宽范围)
            if (weight) {
                if (weight < 20 || weight > 300) {
                    showError('weight', '体重必须在20-300kg之间');
                    console.log('Weight validation failed:', weight);
                    isValid = false;
                }
            }
            
            // 年龄验证
            if (age) {
                if (age < 0 || age > 120) {
                    showError('age', '请输入有效年龄（0-120岁）');
                    console.log('Age validation failed:', age);
                    isValid = false;
                }
            }
            
            // 血压验证 (放宽范围)
            if (systolic) {
                if (systolic < 50 || systolic > 300) {
                    showError('systolic', '收缩压范围应在50-300mmHg之间');
                    console.log('Systolic validation failed:', systolic);
                    isValid = false;
                }
            }
            if (diastolic) {
                if (diastolic < 30 || diastolic > 200) {
                    showError('diastolic', '舒张压范围应在30-200mmHg之间');
                    console.log('Diastolic validation failed:', diastolic);
                    isValid = false;
                }
            }
            
            console.log('Validation result:', isValid); // 调试日志
            return isValid;
        }

        function showError(fieldId, message) {
            console.log('Showing error for:', fieldId, message); // 调试日志
            const field = document.getElementById(fieldId);
            if (!field) {
                console.log('Field not found:', fieldId);
                return;
            }
            
            let errorDiv = field.parentElement.querySelector('.error-message');
            if (!errorDiv) {
                errorDiv = document.createElement('div');
                errorDiv.className = 'error-message';
                field.parentElement.appendChild(errorDiv);
            }
            errorDiv.textContent = message;
            errorDiv.style.display = 'block';
            field.style.borderColor = '#e74c3c';
        }

        // 修改清除错误函数
        function clearError(fieldId) {
            console.log('Clearing error for:', fieldId); // 调试日志
            const field = document.getElementById(fieldId);
            if (!field) {
                console.log('Field not found:', fieldId);
                return;
            }
            
            const errorDiv = field.parentElement.querySelector('.error-message');
            if (errorDiv) {
                errorDiv.style.display = 'none';
            }
            field.style.borderColor = '#ddd';
        }

        // 修改BMI计算函数
        function calculateBMI() {
            const height = document.getElementById('height')?.value;
            const weight = document.getElementById('weight')?.value;
            console.log('Calculating BMI:', { height, weight }); // 调试日志
            
            if (height && weight) {
                const heightInMeters = height / 100;
                const bmi = (weight / (heightInMeters * heightInMeters)).toFixed(1);
                console.log('Calculated BMI:', bmi);
                document.getElementById('bmi').textContent = bmi;
            }
        }

        async function submitForm(event) {
            event.preventDefault();
            console.log('Form submission started'); // 添加调试日志
            
            if (!validateForm()) {
                console.log('Form validation failed'); // 添加调试日志
                return;
            }

            const loading = document.getElementById('loading');
            const submitButton = document.querySelector('button[type="submit"]');
            
            loading.style.display = 'block';
            submitButton.disabled = true;
            
            const formData = new FormData(event.target);
            const data = Object.fromEntries(formData);
            
            // 添加BMI值到数据中
            const bmiElement = document.getElementById('bmi');
            if (bmiElement) {
                data.bmi = bmiElement.textContent;
            }
            
            // 打印完整的表单数据
            console.log('Complete form data:', data);
            
            const jsonData = JSON.stringify(data);
            console.log('JSON data to send:', jsonData);
            
            try {
                console.log('Attempting to send data to server...');
                const response = await fetch('/generate_recommendation', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: jsonData
                });
                
                console.log('Server response received:', response);
                console.log('Response status:', response.status);
                
                if (!response.ok) {
                    throw new Error(`服务器响应错误: ${response.status}`);
                }
                
                const result = await response.json();
                console.log('Parsed response data:', result);
                
                if (result.success) {
                    // 格式化建议内容
                    function formatRecommendation(text) {
                        // 分割不同部分（假设用 ## 分隔标题）
                        const sections = text.split(/##\s+/);
                        let formattedHtml = '';
                        
                        sections.forEach(section => {
                            if (section.trim()) {
                                const lines = section.split('\n');
                                const title = lines[0].trim();
                                const content = lines.slice(1).join('\n').trim();
                                
                                if (title && content) {
                                    formattedHtml += `
                                        <div class="recommendation-section">
                                            <div class="recommendation-title">${title}</div>
                                            <div class="recommendation-content">
                                                ${content.split('\n').map(line => 
                                                    line.trim() ? `<div class="recommendation-item">${line.trim()}</div>` : ''
                                                ).join('')}
                                            </div>
                                        </div>
                                    `;
                                }
                            }
                        });
                        
                        return formattedHtml;
                    }
                    
                    const recommendationElement = document.getElementById('recommendation');
                    if (recommendationElement) {
                        recommendationElement.innerHTML = formatRecommendation(result.recommendation);
                        const resultElement = document.getElementById('result');
                        resultElement.style.display = 'block';
                        resultElement.scrollIntoView({ behavior: 'smooth' });
                        console.log('Recommendation displayed successfully');
                    }
                } else {
                    throw new Error(result.error || '生成建议失败');
                }
            } catch (error) {
                console.error('Detailed error:', error);
                alert('提交失败：' + error.message);
            } finally {
                loading.style.display = 'none';
                submitButton.disabled = false;
                console.log('Form submission completed');
            }
        }
    </script>
</body>
</html> 